//
//  ProblemFeedBackViewController.m
//  Jingjing
//
//  Created by user on 15/11/9.
//  Copyright © 2015年 Mikeshihua. All rights reserved.
//

#import "ProblemFeedBackViewController.h"
#import "sys/utsname.h"
#import <NSString+RemoveEmoji.h>

@interface ProblemFeedBackViewController ()<UITextFieldDelegate,UITextViewDelegate>
{
    UITextView * _textView;
    UITextField *_nameLabelTF;
    
    UITextField *_contactTF;
    
    int keyboardhight;
    
    UIScrollView *_scrollView;
    
    UITextField *_placeholderLabel;
}
@property(nonatomic,strong)UIButton *sendBtn;

@end


@implementation ProblemFeedBackViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self layoutViews];
    
    TopView *topView = [[TopView alloc]initWithFrame:CGRectMake(0.0f, 0.0f, SCREEN_WIDTH, 64.0f)];
    [topView setTitile:@"问题反馈"];
    [self.view addSubview:topView];
    
    UIButton * backBtn = [[UIButton alloc]initWithFrame:CGRectMake(10.0f, 20.0f, 44.0f, 44.0f)];
    [backBtn setImage:[UIImage imageNamed:@"icon_back"] forState:UIControlStateNormal];
    [backBtn addTarget:self action:@selector(backBtnCLick:) forControlEvents:UIControlEventTouchUpInside];
    backBtn.titleLabel.textAlignment = NSTextAlignmentRight;
    [topView addSubview:backBtn];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector (keyboardShow:)
                                                 name: UIKeyboardDidShowNotification object:nil];
    //注册键盘隐藏通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector (keyboardHide:)
                                                 name: UIKeyboardDidHideNotification object:nil];
    
    
}

- (void)layoutViews
{
    _scrollView  = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    _scrollView.backgroundColor = [UIColor hexStringToColor:@"#f3f3f3"];
    [self.view addSubview:_scrollView];
    

    UILabel *problemLabel = [[UILabel alloc] initWithFrame:CGRectMake(24.0f, 60.0f, SCREEN_WIDTH - 32.0f, 30.0f)];
    problemLabel.text = @"反馈意见";
    problemLabel.textAlignment = NSTextAlignmentLeft;
    problemLabel.textColor = kColorTEXT;
    problemLabel.font = [UIFont systemFontOfSize:18.0f];
    [_scrollView addSubview:problemLabel];
    
    
    //弹出留言框
    _textView = [[UITextView alloc]initWithFrame:CGRectMake(16.0f, NH(problemLabel)+16.0f, SCREEN_WIDTH-32.f, 200.0f)];
    _textView.layer.cornerRadius= 5;
    _textView.textColor= kColorTEXT;
    _textView.font= [UIFont fontWithName:@"Arial"size:14.0];
    _textView.delegate= self;
    _textView.backgroundColor = [UIColor whiteColor];
    [_scrollView  addSubview:_textView];
    
    //其次在UITextView上面覆盖个UILable,UILable设置为全局变量。
    _placeholderLabel = [[UITextField alloc]init];
    _placeholderLabel.frame =CGRectMake(8, 8, SCREEN_WIDTH-48.0f, 20.0f);
    _placeholderLabel.placeholder = @"请将您的意见写在这里哦!";
    _placeholderLabel.enabled = NO;//lable必须设置为不可用
    _placeholderLabel.textColor = [UIColor hexStringToColor:@"#BDBDBD"];
    _placeholderLabel.backgroundColor = [UIColor clearColor];
    [_textView addSubview:_placeholderLabel];
    
    
    UIView *contactView = [[UIView alloc]initWithFrame:CGRectMake(16.0f, NH(_textView)+24.0f, SCREEN_WIDTH-32.0f, 60.0f)];
    contactView.backgroundColor = [UIColor whiteColor];
    [_scrollView addSubview:contactView];
    
    UILabel *nameLabel = [[UILabel alloc]initWithFrame:CGRectMake(24.0f, 16.0f, 70.0f, 28.0f)];
    nameLabel.text = @"联系方式";
    nameLabel.textColor = kColorTEXT;
    nameLabel.font = [UIFont systemFontOfSize:16.0f];
    [contactView addSubview:nameLabel];
    
    
    
    _nameLabelTF = [[UITextField alloc] initWithFrame:CGRectMake(NW(nameLabel)+10.0f, 16.0f, SCREEN_WIDTH - 32.0f-24.0f-10.0f-width(nameLabel), 28.0f)];
    _nameLabelTF.delegate = self;
    _nameLabelTF.placeholder = @"(手机号/QQ/邮箱)";
    _nameLabelTF.keyboardType = UIKeyboardTypeDefault;
    _nameLabelTF.clearButtonMode = UITextFieldViewModeWhileEditing;
    _nameLabelTF.borderStyle = UITextBorderStyleNone;
    _nameLabelTF.tag = 1;
    _nameLabelTF.font = [UIFont systemFontOfSize:14.0f];
    _nameLabelTF.layer.cornerRadius = 2;
    [_nameLabelTF addTarget:self action:@selector(nameLabelTFTapped:) forControlEvents:UIControlEventEditingChanged];
    [contactView addSubview:_nameLabelTF];
    

    if (!_sendBtn) {

        _sendBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _sendBtn.frame  = CGRectMake(SCREEN_WIDTH/2-100.0f/2, NH(contactView)+16.0f, 100.0f, 44.0f);
        [_sendBtn setBackgroundColor:kColorOrangeNormal forState:UIControlStateNormal];
        [_sendBtn setTitleColor:[UIColor hexStringToColor:@"#FFFFFF"] forState:UIControlStateNormal];
        [_sendBtn setBackgroundColor:kColorOrangePressed forState:UIControlStateHighlighted];
        [_sendBtn setBackgroundColor:kColorOrangeDisabled forState:UIControlStateDisabled];
        _sendBtn.layer.cornerRadius = 5;
        _sendBtn.layer.masksToBounds = YES;
        _sendBtn.titleLabel.font = [UIFont boldSystemFontOfSize:14.0f];
        [_sendBtn setTitle:@"提交" forState:UIControlStateNormal];
        [_sendBtn addTarget:self action:@selector(send:) forControlEvents:UIControlEventTouchUpInside];
        _sendBtn.enabled = NO;
        [_scrollView addSubview:_sendBtn];
    }

    
}


//提交按钮
-(void)send:(UIButton*)btn
{
    //手机系统版本
    NSString* systemModel = [[UIDevice currentDevice] systemVersion];
    
    // 当前应用软件版本  比如：1.0.1
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    NSString *appNumber = [infoDictionary objectForKey:@"CFBundleShortVersionString"];

    
    if ([AccountTools allIsNumber:_nameLabelTF.text]==NO&&[AccountTools validateEmail:_nameLabelTF.text]==NO&&[AccountTools validatePhoneNumber:_nameLabelTF.text]==NO ) {
        ALERT_VIEW(@"联系方式为QQ号，邮箱，或者手机号");
        return;
    }
    
    
    if (_textView.text.length>200) {
        ALERT_VIEW(@"反馈意见最多只能输入200个字符");
        return;
    }
    
    if (_nameLabelTF.text.length>50) {
        ALERT_VIEW(@"联系方式最多只能输入50个字符");
        return;
    }
    
    [[AnimationIndicator sharedIndicator] startAnimationWithLoadText:@"加载中"];
    [AppGlobalClass PostDataWithNSstring:INSERTFEEDBACK withDictionary:@{@"mobile":_nameLabelTF.text,@"content":_textView.text,@"mobileModel":[self deviceVersion],@"systemModel":systemModel,@"mobileType":@"1",@"appNumber":appNumber} success:^(NSDictionary *dictionary) {
        if([[dictionary objectForKey:@"success"] isEqualToNumber:[NSNumber numberWithBool:TRUE]])
        {
            
            ALERT_VIEW(@"意见反馈成功，我们将尽快为您处理");
            [self.navigationController popViewControllerAnimated:TRUE];
            
        }else
        {
    
            NSString * str = [dictionary objectForKey:@"message"];
            ALERT_VIEW(str);
            
        }
        [[AnimationIndicator sharedIndicator] stopAnimationWithLoadText:@"" withType:TRUE];
    } failure:^(NSError *error) {
        [[AnimationIndicator sharedIndicator] stopAnimationWithLoadText:@"" withType:TRUE];
    } networkerror:^(NSString *networkerror) {
        [[AnimationIndicator sharedIndicator] stopAnimationWithLoadText:@"" withType:TRUE];
    }];
    
    
}

- (void)backBtnCLick:(UIButton*)btn
{
    [[AnimationIndicator sharedIndicator] stopAnimationWithLoadText:@"" withType:TRUE];
    [self.navigationController popViewControllerAnimated:YES];
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [_contactTF resignFirstResponder];
    [_nameLabelTF resignFirstResponder];
    return YES;
}
#pragma mark-textField方法
-(void)nameLabelTFTapped:(id)sender{

    if ([AccountTools isEmpty:_textView.text]==NO&&[AccountTools isEmpty:_nameLabelTF.text]==NO) {
        _sendBtn.enabled = TRUE;
        
    }else{
        _sendBtn.enabled = FALSE;
    }
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    if ([string isIncludingEmoji]) {
        return NO;
    }else{
        NSLog(@" %d | %s | %@",__LINE__,__FUNCTION__,string);
        const char *chs = [string cStringUsingEncoding:NSUTF8StringEncoding];
        NSLog(@" %d | %s | %s",__LINE__,__FUNCTION__,chs);
        
    }
    return YES;
}

#pragma mark-关闭键盘(TextView) 换行时。隐藏键盘
-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    if ([text isIncludingEmoji]) {
        return NO;
    }

    if ([text isEqualToString:@"\n"]) {
        [textView resignFirstResponder];
        return NO;
    }
    return YES;
}

-(void)textViewDidChange:(UITextView *)textView
{
    
    if (textView.text.length == 0) {
        _placeholderLabel.placeholder = @"请将您的意见写在这里哦!";
        _sendBtn.enabled = NO;
        
    }else{
        _placeholderLabel.placeholder = @"";
        
        if ([AccountTools isEmpty:_nameLabelTF.text]==NO) {
            _sendBtn.enabled = YES;
        }
        
    }
}
//- (BOOL)stringContainsEmoji:(NSString *)string
//{
//    __block BOOL returnValue = NO;
//    
//    [string enumerateSubstringsInRange:NSMakeRange(0, [string length])
//                               options:NSStringEnumerationByComposedCharacterSequences
//                            usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
//                                const unichar hs = [substring characterAtIndex:0];
//                                if (0xd800 <= hs && hs <= 0xdbff) {
//                                    if (substring.length > 1) {
//                                        const unichar ls = [substring characterAtIndex:1];
//                                        const int uc = ((hs - 0xd800) * 0x400) + (ls - 0xdc00) + 0x10000;
//                                        if (0x1d000 <= uc && uc <= 0x1f77f) {
//                                            returnValue = YES;
//                                        }
//                                    }
//                                } else if (substring.length > 1) {
//                                    const unichar ls = [substring characterAtIndex:1];
//                                    if (ls == 0x20e3) {
//                                        returnValue = YES;
//                                    }
//                                } else {
//                                    if (0x2100 <= hs && hs <= 0x27ff) {
//                                        returnValue = YES;
//                                    } else if (0x2B05 <= hs && hs <= 0x2b07) {
//                                        returnValue = YES;
//                                    } else if (0x2934 <= hs && hs <= 0x2935) {
//                                        returnValue = YES;
//                                    } else if (0x3297 <= hs && hs <= 0x3299) {
//                                        returnValue = YES;
//                                    } else if (hs == 0xa9 || hs == 0xae || hs == 0x303d || hs == 0x3030 || hs == 0x2b55 || hs == 0x2b1c || hs == 0x2b1b || hs == 0x2b50) {
//                                        returnValue = YES;
//                                    }
//                                }
//                            }];
//    if (returnValue) {
//        NSLog(@" %d | %s | %@",__LINE__,__FUNCTION__,@"emoji");
//    }
//    return returnValue;
//}
- (NSString*)deviceVersion
{
    // 需要#import "sys/utsname.h"
    struct utsname systemInfo;
    uname(&systemInfo);
    NSString *deviceString = [NSString stringWithCString:systemInfo.machine encoding:NSUTF8StringEncoding];
    
  
    
    
    if ([deviceString isEqualToString:@"iPhone1,1"])    return @"iPhone 1G";
    if ([deviceString isEqualToString:@"iPhone1,2"])    return @"iPhone 3G";
    if ([deviceString isEqualToString:@"iPhone2,1"])    return @"iPhone 3GS";
    if ([deviceString isEqualToString:@"iPhone3,1"])    return @"iPhone 4";
    if ([deviceString isEqualToString:@"iPhone3,2"])    return @"Verizon iPhone 4";
    if ([deviceString isEqualToString:@"iPhone4,1"])    return @"iPhone 4S";
    if ([deviceString isEqualToString:@"iPhone5,2"])    return @"iPhone 5";
    if ([deviceString isEqualToString:@"iPhone6,1"])    return @"iPhone 5S";
    if ([deviceString isEqualToString:@"iPhone7,2"])    return @"iPhone 6";
    if ([deviceString isEqualToString:@"iPhone7,1"])    return @"iPhone6 Plus";
    if ([deviceString isEqualToString:@"iPhone8,2"])    return @"iPhone6s Plus";
    if ([deviceString isEqualToString:@"iPhone8,1"])    return @"iPhone6s ";
    if ([deviceString isEqualToString:@"iPod1,1"])      return @"iPod Touch 1G";
    if ([deviceString isEqualToString:@"iPod2,1"])      return @"iPod Touch 2G";
    if ([deviceString isEqualToString:@"iPod3,1"])      return @"iPod Touch 3G";
    if ([deviceString isEqualToString:@"iPod4,1"])      return @"iPod Touch 4G";
    if ([deviceString isEqualToString:@"iPad1,1"])      return @"iPad";
    if ([deviceString isEqualToString:@"iPad2,1"])      return @"iPad 2 (WiFi)";
    if ([deviceString isEqualToString:@"iPad2,2"])      return @"iPad 2 (GSM)";
    if ([deviceString isEqualToString:@"iPad2,3"])      return @"iPad 2 (CDMA)";
    if ([deviceString isEqualToString:@"iPad3,4"])      return @"iPad 4 (WiFi)";
    if ([deviceString isEqualToString:@"i386"])         return @"Simulator";
    if ([deviceString isEqualToString:@"x86_64"])       return @"Simulator";
    
    
    
    return deviceString;
}

//键盘下降
- (void)keyboardHide:(NSNotification *)noti
{
    
    
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:[[noti.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue]];
    [UIView setAnimationCurve:7];
//    _scrollView.contentOffset = CGPointMake(0, -16);
    _scrollView.contentSize = CGSizeMake(SCREEN_WIDTH, SCREEN_HEIGHT);
    [UIView commitAnimations];
}

//键盘升起
- (void)keyboardShow:(NSNotification *)noti
{
    NSValue *value = [noti.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardFrame = [value CGRectValue];
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:[[noti.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue]];
    [UIView setAnimationCurve:7];
    if (keyboardFrame.origin.y != SCREEN_HEIGHT) {
        CGFloat a = _scrollView.frame.size.height + _scrollView.frame.origin.y+80.0f;
        if (a < keyboardFrame.origin.y) {
//            _scrollView.contentOffset = CGPointMake(0, -16);
            _scrollView.contentSize = CGSizeMake(SCREEN_WIDTH, SCREEN_HEIGHT);
        }else
        {
//            _scrollView.contentOffset = CGPointMake(0, 100);
        _scrollView.contentSize = CGSizeMake(SCREEN_WIDTH, SCREEN_HEIGHT*1.5);
        }
        
    }
    
    [UIView commitAnimations];
    
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.tabBarController.tabBar.hidden = YES;
    
    
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    self.tabBarController.tabBar.hidden = NO;
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
